package logic

import (
	"MyBlogv2/blog-common/HttpCode"
	"MyBlogv2/blog-common/es"
	"MyBlogv2/blog-common/models"
	"context"
	"github.com/jinzhu/copier"
	"time"

	"MyBlogv2/Servers/Article/article"
	"MyBlogv2/Servers/Article/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PublishArticleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPublishArticleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PublishArticleLogic {
	return &PublishArticleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PublishArticleLogic) PublishArticle(in *Article.PublishArticleRequest) (*Article.CommonResponse, error) {
	var articleDto models.ArticleDto
	copier.Copy(&articleDto, &in.ArticleDto)
	userId := in.UserId
	var article models.Article
	article.UserId = int(userId)
	copier.Copy(&article, &articleDto)

	var articleSearch models.ArticleEs
	var categoryName string
	var tagsName []string
	models.Db.Model(new(models.Category)).Select("category_name").Where("id = ?", article.CategoryId).Find(&categoryName)
	models.Db.Model(new(models.Tag)).Select("tag_name").Where("id in (?)", articleDto.TagId).Find(&tagsName)
	copier.Copy(&articleSearch, &articleDto)
	articleSearch.TagsName = tagsName
	articleSearch.CategoryName = categoryName
	articleSearch.CreateTime = models.MyTime(time.Now())

	if article.Id == 0 {
		models.Db.Model(new(models.Article)).Create(&article)
		es.SaveArticle(articleSearch, article.Id)
	} else {
		models.Db.Model(new(models.Article)).Where("id = ?", article.Id).Updates(&article)
		es.UpdateArticle(articleSearch, article.Id)
	}
	sql := "delete from t_article_tag where article_id = ?"
	models.Db.Exec(sql, article.Id)
	for _, v := range articleDto.TagId {
		var articleTag models.ArticleTag
		articleTag.ArticleId = articleDto.Id
		articleTag.TagId = v
		models.Db.Model(new(models.ArticleTag)).Create(&articleTag)
	}

	return &Article.CommonResponse{
		Code: int64(HttpCode.SUCCESS),
	}, nil
}
